package com.tongfusoft.document.doc.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tongfuosft.document.system.notice.service.INoticeService;
import com.tongfusoft.da.pagehelper.PageInfo;
import com.tongfusoft.da.template.service.impl.DataTemplateServiceImpl;
import com.tongfusoft.document.doc.service.IDocService;
import com.tongfusoft.document.doc.service.IFileStroageService;
import com.tongfusoft.document.entity.BigFiles;
import com.tongfusoft.document.entity.DocHistory;
import com.tongfusoft.document.entity.Docs;
import com.tongfusoft.document.entity.Folders;
import com.tongfusoft.document.entity.Notice;
import com.tongfusoft.document.entity.SecurityGroup;
import com.tongfusoft.document.entity.UserFollows;
import com.tongfusoft.document.entity.Users;
import com.tongfusoft.document.manager.folders.service.IFoldersService;
import com.tongfusoft.document.personalCenter.myFollow.service.IMyFollowService;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.utils.FileUtils;

@Service("docService")
public class DocServiceImpl extends DataTemplateServiceImpl<Docs> implements IDocService {

	@Autowired
	public IFileStroageService fileStroageService;
	@Autowired
	@Qualifier("noticeService")
	public INoticeService noticeService;
	@Autowired
	@Qualifier("userFollowService")
	public IMyFollowService userFollowService;

	@Override
	public void createDoc(MultipartFile file, Docs doc, Users user) {

		try {

			doc.setDocVersion(1);
			doc.setCreatedBy(user.getUserId());
			doc.setLastUpdBy(user.getUserId());
			doc.setSubmitter(user.getUserId());
			doc.setCreatedDate(new Timestamp(new Date().getTime()));
			doc.setLastUpdDate(new Timestamp(new Date().getTime()));
			if(doc.getUploadModel().equals("1")){
				doc.setDocSize(new BigDecimal(file.getSize()));
				doc.setOriginalName(file.getOriginalFilename());
				doc.setDocPath(this.fileStroageService.stroage(doc,file.getInputStream(), file.getOriginalFilename()));
				doc.setDocSubffix(FileUtils.getExtensionName(file.getOriginalFilename()).toLowerCase());
			}else{
				BigFiles bigFile  = new BigFiles();
				bigFile.setId(doc.getSelectFileId());
				bigFile = super.selectOne("selectBigFileById", bigFile);
				
				if(bigFile==null){
					
					throw new ServiceException("file_empty");
				}
				doc.setDocSize(new BigDecimal(bigFile.getFileSize()));
				doc.setDocSubffix(FileUtils.getExtensionName(bigFile.getFileName()).toLowerCase());
				doc.setOriginalName(bigFile.getFileName());
				doc.setDocPath(this.fileStroageService.stroage(doc,new FileInputStream(new File(bigFile.getFilePath())), bigFile.getFileName()));
				new File(bigFile.getFilePath()).delete();
				
				super.update("updateFileSelected", bigFile);
			}
			
			super.insert("addDoc", doc);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

	@Override
	public void deleteDoc(String docName, String docId, Users user) {

		
		if (StringUtils.isNotEmpty(docId)) {
			DocHistory doc = new DocHistory();
			doc.setLastUpdBy(user.getUserId());
			doc.setLastUpdDate(new Timestamp(new Date().getTime()));
			doc.setDocName(docName);
			doc.setDocId(docId);

			super.update("deleteDocHistory", doc);

		} else {

			Docs doc = new Docs();
			doc.setLastUpdBy(user.getUserId());
			doc.setLastUpdDate(new Timestamp(new Date().getTime()));
			doc.setDocName(docName);
			super.update("deleteDoc", doc);

			DocHistory doch = new DocHistory();
			doch.setLastUpdBy(user.getUserId());
			doch.setLastUpdDate(new Timestamp(new Date().getTime()));
			doch.setDocName(docName);
			super.update("deleteDocHistory", doch);
		}
	}

	@Override
	public PageInfo<Docs> searchDoc(Docs doc, Users user, int pageSize, int pageIndex) {
		doc.setSelectUser(user.getUserId());

		return super.findPage("docList", doc, pageSize, pageIndex);

	}

	@Override
	public Docs getDoc(Docs doc, Users user) {
		
		doc =  super.selectOne("getDocUpdateetail", doc);
		if(StringUtils.isNotEmpty(doc.getDocFolder())){
			doc.setFolderPath("/"+this.getTreeParents(doc.getDocFolder()));
		}
		return doc;
	}

	@Override
	public String profileId(String docName) {
		return this.selectOne("getProfileIdByDocName", docName);
	}

	@Override
	public void updateDoc(MultipartFile file, Docs doc, Users user) {

		try {

			if (file != null) {

				doc.setOriginalName(file.getOriginalFilename());
				doc.setDocSize(new BigDecimal(file.getSize()));
				doc.setLastUpdBy(user.getUserId());
				doc.setLastUpdDate(new Timestamp(new Date().getTime()));
				doc.setCreatedBy(user.getUserId());
				doc.setCreatedDate(new Timestamp(new Date().getTime()));
				doc.setDocPath(this.fileStroageService.stroage(doc,file.getInputStream(), file.getOriginalFilename()));
				doc.setSubmitter(user.getUserId());
				doc.setDocSubffix(FileUtils.getExtensionName(file.getOriginalFilename()).toLowerCase());
				
				super.insert("saveDocHistory", doc);
				super.update("updateDocMetaDateAndFile", doc);

			}else if(StringUtils.isNotEmpty(doc.getSelectFileId())){
				
				doc.setLastUpdBy(user.getUserId());
				doc.setLastUpdDate(new Timestamp(new Date().getTime()));
				doc.setCreatedBy(user.getUserId());
				doc.setCreatedDate(new Timestamp(new Date().getTime()));
				doc.setSubmitter(user.getUserId());
				
				BigFiles bigFile  = new BigFiles();
				bigFile.setId(doc.getSelectFileId());
				bigFile = super.selectOne("selectBigFileById", bigFile);
				
				if(bigFile==null){
					
					throw new ServiceException("file_empty");
				}
				doc.setDocSize(new BigDecimal(bigFile.getFileSize()));
				doc.setDocSubffix(FileUtils.getExtensionName(bigFile.getFileName()).toLowerCase());
				doc.setOriginalName(bigFile.getFileName());
				doc.setDocPath(this.fileStroageService.stroage(doc,new FileInputStream(new File(bigFile.getFilePath())), bigFile.getFileName()));
				new File(bigFile.getFilePath()).delete();
				
				super.update("updateFileSelected", bigFile);
				super.insert("saveDocHistory", doc);
				super.update("updateDocMetaDateAndFile", doc);
				
			} else {

				doc.setLastUpdBy(user.getUserId());
				doc.setLastUpdDate(new Timestamp(new Date().getTime()));
				super.update("updateDocMetaDate", doc);
			}

			Notice notice = new Notice();
			UserFollows userFollows = new UserFollows();
			userFollows.setDocName(doc.getDocName());
			notice.setDocName(doc.getDocName());
			List<UserFollows> list = this.userFollowService.getUserByDocName(userFollows);
			for (UserFollows uf : list) {
				notice.setUserId(uf.getLastUpdBy());
				this.noticeService.createNotice(notice, user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}

	}

	@Override
	public List<SecurityGroup> docEditGroupByUser(String userId) {

		return super.selectList("docEditGroupByUser", userId);

	}

	@Override
	public DocHistory viewDocDetail(DocHistory doc, Users user) {
		
		
		if (StringUtils.isEmpty(doc.getDocId())) {
			doc = super.selectOne("viewDocDetailBydocName", doc);
			
		} else {
			doc= super.selectOne("viewDocDetailBydocId", doc);
		}
		if(StringUtils.isNotEmpty(doc.getDocFolder())){
			doc.setFolderPath("/"+this.getTreeParents(doc.getDocFolder()));
		}
	
		return doc;
	}

	@Override
	public List<DocHistory> DocsHistoryList(String docName) {
		return super.selectList("docsHistoryList", docName);
	}
	
	private String getTreeParents(String nodeId){
		if(StringUtils.isEmpty(nodeId)){
			return "";
		}
		Folders folder = new Folders();
		folder.setFolderId(nodeId);
		folder = super.selectOne("getParentFolder", folder);
		if(folder!=null){
			String path=folder.getFolderName()+"/";
			if(!StringUtils.isEmpty(folder.getParentFolderId())){
				
				path = getTreeParents(folder.getParentFolderId())+path;
			}
			return path;
		}else{
			return "";
		}
		
		
	}

}
